"""
正规方程就是直接用矩阵求解,不能解决过拟合
数据很多超过10万,推荐梯度下降
"""
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error

def linear1():
    """
    正规方程的优化方法对波士顿房价进行预测
    """
    # 1 获取数据
    boston = load_boston()
    # 2 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
    # 3 标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 4 预估器
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)
    # 5 得出模型
    print("正规方程权重系数为: ", estimator.coef_)
    print("正规方程偏置为: ", estimator.intercept_)
    # 6 模型评估
    y_predict = estimator.predict(x_test)
    print("正规方程预测房价: ", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("正规方程均方误差为: ", error)

def linear2():
    """
    梯度下降的优化方法对波士顿房价进行预测
    """
    # 1 获取数据
    boston = load_boston()
    # 2 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
    # 3 标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 4 预估器 梯度下降
    estimator = SGDRegressor()
    estimator.fit(x_train, y_train)
    # 5 得出模型
    print("梯度下降权重系数为: ", estimator.coef_)
    print("梯度下降偏置为: ", estimator.intercept_)
    # 6 模型评估
    y_predict = estimator.predict(x_test)
    print("梯度下降预测房价: ", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("梯度下降均方误差为: ", error)

def linear3():
    """
    岭回归的优化方法对波士顿房价进行预测
    """
    # 1 获取数据
    boston = load_boston()
    # 2 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
    # 3 标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 4 预估器
    estimator = Ridge()
    estimator.fit(x_train, y_train)
    # 5 得出模型
    print("岭回归权重系数为: ", estimator.coef_)
    print("岭回归偏置为: ", estimator.intercept_)
    # 6 模型评估
    y_predict = estimator.predict(x_test)
    print("岭回归预测房价: ", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("岭回归均方误差为: ", error)

if __name__ == '__main__':
    linear1()
    linear3()